/**
 * axios
 */
import axios from 'axios'
import qs from 'qs'
import { ElMessageBox, ElMessage } from 'element-plus'
import Auth from '@/utils/auth'

let messageBoxShow = false
// 错误信息的处理方法
const errorHandle = res => {
  switch (res.status) {
    case 400:
      ElMessage.error(res.data.message)
      break
    case 401:
      console.log('（未授权）， 请求要求身份验证身份')
      if (!messageBoxShow) {
        messageBoxShow = true
        ElMessageBox.confirm(res.data.message || '登录信息过期, 是否重新登录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            Auth.authorize()
            ElMessageBox.close()
            // window.location.reload(true)
            messageBoxShow = false
          })
          .catch(() => {
            ElMessageBox.close()
            messageBoxShow = false
          })
      }
      break
    case 403:
      console.log('（禁止）服务拒绝请求')
      break
    case 404:
      console.log('网络请求地址错误')
      break
    default:
      ElMessage.error(res.data)
      break
  }
}

// 统一配置
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 36000, // request timeout
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json;utf-8'
  }
})

// 请求拦截
service.interceptors.request.use(
  config => {
    const token = Auth.getAccessToken()
    if (token && token !== undefined && !config.headers.Authorization) {
      config.headers.Authorization = 'Bearer ' + token
    }
    if (config.headers['Content-Type'].startsWith('application/x-www-form-urlencoded')) {
      if (config.data) {
        config.data = qs.stringify(config.data)
      }
    } else {
      if (config.data) {
        config.data = qs.parse(config.data)
      }
    }
    // 配置
    // if ((config.method === 'POST' || config.method === 'post') && !config.headers['Content-Type']) {
    //   config.headers['Content-Type'] = 'application/json'
    //   if (!(config.data instanceof Array)) {
    //     config.data = qs.parse(config.data)
    //   }
    // } else if ((config.method === 'PUT' || config.method === 'put')) {
    //   config.headers['Content-Type'] = 'application/json'
    //   config.data = qs.parse(config.data)
    // }
    // if (!config.headers['Content-Type'] || config.headers['Content-Type'] === undefined) {
    //   config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    //   config.data = qs.stringify(config.data)
    // }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截
service.interceptors.response.use(
  // 成功
  response => {
    return response.status === 200
      ? Promise.resolve(response.data)
      : Promise.reject(response.data)
  },
  // 失败
  error => {
    const { response } = error // ES6解构
    if (response) {
      errorHandle(response)
      return Promise.reject(response)
    } else {
      console.log('请求中断或者断网了')
    }
  }
)

export default service
